package org.hilo.boot.app.config;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;

import org.hilo.boot.core.logback.SwTrace;

/**
 * 
 * @author zollty
 * @since 2020年11月26日
 */
public class OnEnvironmentPreparedListener implements SmartApplicationListener {
    // 比解析spring配置文件的listener优先级低
    // private int order = ConfigFileApplicationListener.DEFAULT_ORDER + 1;
    // 比解析apollo配置的listener优先级低
    // see ApolloApplicationListener.DEFAULT_ORDER
    private int order = LoggingApplicationListener.DEFAULT_ORDER;
    
    private boolean inited;
    
    public void setOrder(int order) {
        this.order = order;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType);
    }
    
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
        }
    }
    
    private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
        if (!this.inited) {
            String swa = event.getEnvironment().getProperty("hilo.skywalking.enable");
            if ("true".equalsIgnoreCase(swa)) {
                SwTrace.initLogbackTraceExtention();
            }
            inited = true;
        }
    }

}
